import { judgeCode } from './errcode.js';
import { BaseURL } from './baseurl.js';
let _this;

/**
 *  loadingRequestCount  请求次数的变量，用来记录当前页面总共请求的次数
 *  loadingShow   ,  显示loading的函数 并且记录请求次数 ++
 */
let loadingRequestCount = 0;
const loadingShow = (setting) => {
	if (loadingRequestCount === 0) {
		let config = {
            title: '',
            mask:true
		};
		if (setting) {
			Object.keys(config).forEach((key, index) => {
				if (setting.hasOwnProperty(key)) {
					config[key] = setting[key];
				}
			});
		}
		uni.showLoading(config);
	}
	loadingRequestCount++;
};

/**
 *   隐藏loading的函数，并且记录请求次数
 */
const loadingHide = () => {
	if (loadingRequestCount <= 0) return;
	loadingRequestCount--;
	if (loadingRequestCount === 0) {
		setTimeout(() => {
			//延迟执行解决多个请求时，页面首次加载，loading会闪烁
			uni.hideLoading();
		}, 800);
	}
};

/**
 *  loginFailFlag   登录失效Modal弹窗只显示一次
 */
let loginFailFlag = 0;
const showModal = (code,loadingEle) => {
    let { tokenExpired } = getCacheData();
    if(tokenExpired == 2) {
        if(loadingEle){
            loadingEle.hide()
        }
    }else {
        loginFailFlag += 1;
        if (loginFailFlag > 1) return;
        setTimeout(() => {

            let codeType_1 = [401,404,1014],  codeType_2 = [1010] ,  
            codeType_3 = [1011],codeType_4 = [1007], codeType_5 = [2004]
            
            if(codeType_3.indexOf(code)>-1){  //不需要弹窗
                uni.navigateBack()
                return;
            } else if( codeType_2.indexOf(code)>-1){
                uni.showModal({
                    title: '温馨提示',
                    showCancel: true,
                    content: '授权失败，账号异常，需要重新登录',
                    confirmText: '确定',
                    success: function(res) {
                        if (res.confirm) {
                            loginFailFlag -= 1;
                            uni.clearStorageSync();
                            uni.reLaunch({ url: './index'})
                        } else if (res.cancel) {
                            loginFailFlag -= 1;
                        }
                    }
                });
                return;
            }else if(codeType_1.indexOf(code)>-1){
                uni.showModal({
                    title: '温馨提示',
                    content: '请求未授权，请重新登录授权',
                    success: function(res) {
                        if (res.confirm) {
                            loginFailFlag -= 1;
                            uni.clearStorageSync();
                            uni.reLaunch({ url: './index'})
                        } else if (res.cancel) {
                            loginFailFlag = 0;
                            if(loadingEle){
                                loadingEle.hide()
                            }
                        }
                    }
                });
                return
            }else if(codeType_5.indexOf(code)>-1){
                uni.showModal({
                    title: '温馨提示',
                    content: '用户不存在',
                    success: function(res) {
                        if (res.confirm) {
                            loginFailFlag -= 1;
                            uni.clearStorageSync();
                            uni.reLaunch({ url: './index'})
                        } else if (res.cancel) {
                            loginFailFlag = 0;
                            if(loadingEle){
                                loadingEle.hide()
                            }
                        }
                    }
                });
                return
            }else if(codeType_4.indexOf(code)>-1){
                uni.showModal({
                    title: '温馨提示',
                    showCancel: false,
                    content: '登录已失效，请重新登录',
                    confirmText: '确定',
                    success: function(res) {
                        if (res.confirm) {
                            uni.clearStorageSync();
                            uni.reLaunch({ url: './index'})
                        }
                    }
                });
                return
            }
            uni.showModal({
                title: '温馨提示',
                content: '登录已失效，请重新登录',
                success: function(res) {
                    if (res.confirm) {
                        loginFailFlag -= 1;
                        uni.clearStorageSync();
                        uni.reLaunch({ url: './index'})
                    } else if (res.cancel) {
                        loginFailFlag = 0;
                        if(loadingEle){
                            loadingEle.hide()
                        }
                    }
                }
            });
        }, 1500);
    }
};

/**
 *  get 请求
 *  url     api地址
 *  header  请求头
 *  loadingText  下载显示的文字， 默认空
 *  params  请求参数
 */
function GET(url, header, loadingText, params, loadingEle) {
	var promise = new Promise((resolve, reject) => {
		_this = this;
        loadingText &&  loadingShow({ title: loadingText ? loadingText : ''  });
		var { token, time, refreshToken, rightNow, tokenExpired } = getCacheData();
		if (tokenExpired == 0) {
			// 有token,未过期
			header['ykt-auth'] = token;
		} else if (tokenExpired == 1) {
			// 有token,过期
			_this.POSTTOKEN().then((res) => {
                let token = `${res.data.tokenType} ${res.data.accessToken}`;
                header['ykt-auth'] = token;
                apiAxios(
                    url,
                    header,
                    loadingText,
                    params,
                    { resolve: resolve, reject: reject, method: 'GET' },
                    loadingEle
                );
            })
            .catch((err) => {});
            return
		} else if (tokenExpired == 2){   
            //没有token

        }
		apiAxios(url, header, loadingText, params, { resolve: resolve, reject: reject, method: 'GET' }, loadingEle);
	});

	return promise;
}


/**
 *  刷新token 请求
 *  url     api地址
 *  header  请求头
 *  loadingText  下载显示的文字， 默认空
 *  params  请求参数
 */
function POSTTOKEN() {
	var promise = new Promise((resolve, reject) => {
		_this = this;
		var { token, time, refreshToken, rightNow } = getCacheData();
		let header = {};
		header['content-type'] = 'application/json';
		header['Authorization'] = 'Basic dsdsadsdsadsdsd12354546546546545';
		uni.request({
			url: BaseURL + 'token/refresh',
			data: {
				grantType: 'refresh_token',
				refreshToken: refreshToken
			},
			method: 'POST',
			header: header,
			success: function(res) {
				if (judgeCode(res.data.code).status) {
					let token = `${res.data.data.tokenType} ${res.data.data.accessToken}`;
					uni.setStorageSync('token', token);
					uni.setStorageSync('refreshToken', res.data.data.refreshToken);
					uni.setStorageSync('time', Date.parse(new Date()));
					uni.setStorageSync('userId', res.data.data.userId);
					resolve(res.data);
				} else if (res.data.code == 1010 || res.data.code == 1014) {
					uni.showModal({
						title: '温馨提示',
						showCancel: true,
						content: '授权失败，账号异常，需要退出重新登录',
						confirmText: '确定',
						success: function(res) {
							if (res.confirm) {
                                uni.reLaunch({ url: '../pages/home/index'})
							}
						}
					});
				}else if(res.data.code == 401 || res.data.code == 2004){
                    reject(res.data);
                    showModal(res.data.code);
                }else if(res.data.code == 1006 ){
                    reject(res.data);
                    showModal(res.data.code);
                }else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						mask: true,
						duration: 3000
					});
					reject(res.data);
				}
			},
			fail: function(e) {
                uni.showModal({
                    title: '',
                    showCancel: true,
                    content: '网络好像有点问题，请检查后重试,请重新登录',
                    confirmText: '确定',
                    success: function(res) {
                        if (res.confirm) {
                            loginFailFlag -= 1;
                            uni.clearStorageSync();
                            uni.reLaunch({ url: './index'})
                        } else if (res.cancel) {
                            loginFailFlag -= 1;
                        }
                    }
                });
                reject(e);
			}
		});
	});
	return promise;
}

/**
 *  post 请求
 *  url     api地址
 *  header  请求头
 *  loadingText  下载显示的文字， 默认空
 *  params  请求参数
 */
function POST(url, header, loadingText, params, ajaxType) {
	var promise = new Promise((resolve, reject) => {
		_this = this;
		loadingText &&  loadingShow({ title: loadingText ? loadingText : ''  });
		var { token, time, refreshToken, rightNow, tokenExpired } = getCacheData();
		if (tokenExpired == 0) {
			// 有token,未过期
			header['ykt-auth'] = token;
		} else if (tokenExpired == 1) {
			// 有token,过期
			_this
				.POSTTOKEN()
				.then((res) => {
					let token = `${res.data.tokenType} ${res.data.accessToken}`;
					header['ykt-auth'] = token;
					apiAxios(url, header, loadingText, params, { resolve: resolve, reject: reject, method: 'POST' });
				})
				.catch((err) => {});
			return;
		}  else if (tokenExpired == 2){
                // 没有token

        }
		apiAxios(url, header, loadingText, params, { resolve: resolve, reject: reject, method: 'POST' });
	});
	return promise;
}

/**
 *  put 请求
 *  url     api地址
 *  header  请求头
 *  loadingText  下载显示的文字， 默认空
 *  params  请求参数
 */
function PUT(url, header, loadingText, params) {
	var promise = new Promise((resolve, reject) => {
		_this = this;
		loadingText &&  loadingShow({ title: loadingText ? loadingText : ''  });
		var { token, time, refreshToken, rightNow, tokenExpired } = getCacheData();
		if (tokenExpired == 0) {
			// 有token,未过期
			header['ykt-auth'] = token;
		} else if (tokenExpired == 1) {
			// 有token,过期
			_this
				.POSTTOKEN()
				.then((res) => {
					let token = `${res.data.tokenType} ${res.data.accessToken}`;
					header['ykt-auth'] = token;
					apiAxios(url, header, loadingText, params, { resolve: resolve, reject: reject, method: 'PUT' });
				})
				.catch((err) => {});
			return;
		} else if (tokenExpired == 2 ){
            // 没有token
        }
            
		apiAxios(url, header, loadingText, params, { resolve: resolve, reject: reject, method: 'PUT' });
	});
	return promise;
}

/**
 *  delete 请求
 *  url     api地址
 *  header  请求头
 *  loadingText  下载显示的文字， 默认空
 *  params  请求参数
 */
function DELETE(url, header, loadingText, params) {
	var promise = new Promise((resolve, reject) => {
		_this = this;
		var text = loadingText ? loadingText : '';
		loadingText &&  loadingShow({ title: loadingText ? loadingText : ''  });
		var { token, time, refreshToken, rightNow, tokenExpired } = getCacheData();
		if (tokenExpired == 0) {
			// 有token,未过期
			header['ykt-auth'] = token;
		} else if (tokenExpired == 1) {
			// 有token,过期
			_this
				.POSTTOKEN()
				.then((res) => {
					let token = `${res.data.tokenType} ${res.data.accessToken}`;
					header['ykt-auth'] = token;
					apiAxios(url, header, loadingText, params, { resolve: resolve, reject: reject, method: 'DELETE' });
				})
				.catch((err) => {});
			return;
		} else if (tokenExpired == 2 ){
            // 没有token

        }
		apiAxios(url, header, loadingText, params, { resolve: resolve, reject: reject, method: 'DELETE' });
	});
	return promise;
}

/**
 *  downloadFile  下载文件
 *  url     api地址
 *  header  请求头
 *  loadingText  下载显示的文字， 默认空
 *  params  请求参数
 */
function downloadFile(url, header, loadingText, params,callback) {
	var promise = new Promise((resolve, reject) => {
		_this = this;
        loadingText &&  loadingShow({ title: loadingText ? loadingText : ''  });
		if (url.indexOf('https') > -1 || url.indexOf('http') > -1) {
			var newUrl = url;
		} else {
			var newUrl = BaseURL + url;
		}

		var { token, time, refreshToken, rightNow, tokenExpired } = getCacheData();
		if (tokenExpired == 0) {
			// 有token,未过期
			header['ykt-auth'] = token;
		} else if (tokenExpired == 1) {
			// 有token,过期
			_this
				.POSTTOKEN()
				.then((res) => {
					let token = `${res.data.tokenType} ${res.data.accessToken}`;
					header['ykt-auth'] = token;
					apiAxios(newUrl, header, loadingText, params, {
						resolve: resolve,
						reject: reject,
						method: 'DOWNLOAD'
					});
				})
				.catch((err) => {});
			return;
		} 
		apiAxiosFile(url, header, loadingText, params, { resolve: resolve, reject: reject, method: 'DOWNLOAD' },callback);
	});
	return promise;
}

/**
 *  uploadFile  上传文件
 *  url     api地址
 *  header  请求头
 *  loadingText  下载显示的文字， 默认空
 *  params  请求参数
 */
function uploadFile(url, header, loadingText, params) {
	var promise = new Promise((resolve, reject) => {
		_this = this;
		loadingText &&  loadingShow({ title: loadingText ? loadingText : ''  });
		var { token, time, refreshToken, rightNow, tokenExpired } = getCacheData();
		if (tokenExpired == 0) {
			// 有token,未过期
			header['ykt-auth'] = token;
		} else if (tokenExpired == 1) {
			// 有token,过期
			_this
				.POSTTOKEN()
				.then((res) => {
					let token = `${res.data.tokenType} ${res.data.accessToken}`;
					header['ykt-auth'] = token;
					apiAxios(url, header, loadingText, params, { resolve: resolve, reject: reject, method: 'UPLOAD' });
				})
				.catch((err) => {});
			return;
		} else if (tokenExpired == 2){
            // 没有token

        }
		apiAxiosFile(url, header, loadingText, params, { resolve: resolve, reject: reject, method: 'UPLOAD' });
	});
	return promise;
}

/**
 * url , 请求接口
 * header
 * loadingText  加载文本
 * params 参数
 * initData  , promise （ resolve  reject ） , method(方法)
 */
const apiAxios = (url, header, loadingText, params, initData, loadingEle) => {  
	var resolve = initData.resolve,
		reject = initData.reject,
		method = initData.method;
	switch (method) {
		case 'GET':
			var headers = header || {
				'Content-Type': 'application/x-www-form-urlencoded'
			};
			break;
		case 'POST':
			var headers = header || {
				'Content-Type': 'application/x-www-form-urlencoded'
			};
			break;
		case 'PUT':
			var headers = header || {
				'Content-Type': 'application/x-www-form-urlencoded'
			};
			break;
		case 'DELETE':
			var headers = header || {
				'Content-Type': 'application/x-www-form-urlencoded'
			};
			break;
	}

	headers['clientType'] = 'MOBILE';
    let ajaxUrl = ''

	uni.request({
		url: url.indexOf('https') > -1 || url.indexOf('http') > -1 ?  url :  BaseURL + url,
		data: params,
		method: method,
		responseType: url == 'v2/open/class/invite-qrcode' ? 'arraybuffer' : 'text',
		header: headers,
		success: function(res) {
			loadingHide();
			// if(loadingEle){
			// 	loadingEle.close()
            // }
			if (url == 'v1/open/class/invite-qrcode' && res.statusCode == 200 ) {
				let url = 'data:image/png;base64,' + uni.arrayBufferToBase64(res.data);
				resolve(url);
				return;
			}

			if (judgeCode(res.data.code).status || ( ((url.indexOf('token/phoneNumber') > -1) || (url.indexOf('token/miniapp') > -1) || (url.indexOf('token/refresh') > -1)) && ((res.data.code == 2006) || (res.data.code == 2007)))) {
				resolve(res.data);
			} else if (res.data.code == 1011) {
				uni.showToast({
					title: res.data.msg,
					icon: 'none',
					mask: true,
					duration: 2000
                });
                reject(res.data);
			} else if (url.indexOf('/sys/users/') > -1 || res.data.code == 1010 || res.data.code == 1014) {
				showModal(res.data.code);
			} else if(res.data.code == 401 || res.data.code == 404){
                reject(res.data);
                showModal(res.data.code);
            } else {
                if( url.indexOf('v1/open/classroom/current') > -1 && res.data.code == 1){
                    reject(res.data);
                    return
                }
                uni.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    mask: true,
                    duration: 3000
                });
				reject(res.data);
			}
		},
		fail: function(e) {
			loadingHide();
			if (loadingEle) {
				loadingEle.close();
			}
			uni.showToast({
				title: '网络好像有点问题，请检查后重试！',
				icon: 'none',
				mask: true,
				duration: 3000
			});
			reject(e);
		}
	});
};

/**
 * url , 请求接口
 * header
 * loadingText
 * params 参数
 * initData  , promise （ resolve  reject ） ,method(方法)    
 */
const apiAxiosFile = (url, header, loadingText, params, initData,callback) => {
	var resolve = initData.resolve,
		reject = initData.reject,
		method = initData.method;
	switch (method) {
		case 'DOWNLOAD':
			let downloadTask = uni.downloadFile({
				url: url,
				header: header || {},
				success: function(res) {
					loadingHide();
					if (judgeCode(res.statusCode).status) {
						resolve(res,downloadTask);
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							mask: true,
							duration: 3000
                        });
						reject(res);
					}
				},
				fail: function(e) {
					loadingHide();
					uni.showToast({
						title: '网络好像有点问题，请检查后重试！',
						icon: 'none',
						mask: true,
						duration: 2000
					});
					reject(e);
				}
            });

            downloadTask.onProgressUpdate((res) => {
                // console.log('下载进度' + res.progress);
                // console.log('已经下载的数据长度' + res.totalBytesWritten);
                // console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
                callback(res.progress)
                // 测试条件，取消下载任务。
                // if (res.progress > 50) {
                //     downloadTask.abort();
                // }
            });
            // downloadTask.abort();
			break;
		case 'UPLOAD':
			uni.uploadFile({
				url: BaseURL + url,
				filePath: params.filePath,
				name: 'file',
				formData: params.formData,
				header: header || {},
				success: function(res) {
					var result = JSON.parse(res.data);
					loadingHide();
					if (judgeCode(result.code).status) {
						resolve(result);
					} else {
						uni.showToast({
							title: result.msg,
							icon: 'none',
							mask: true,
							duration: 3000
						});
						reject(result);
					}
				},
				fail: function(e) {
					loadingHide();
					uni.showToast({
						title: '网络好像有点问题，请检查后重试！',
						icon: 'none',
						mask: true,
						duration: 2000
					});
					reject(e);
				}
			});
			// uploadTask.onProgressUpdate((res) => {
			// 	console.log('上传进度' + res.progress);
			// 	console.log('已经上传的数据长度' + res.totalBytesSent);
			// 	console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

			// 	// 测试条件，取消上传任务。
			// 	if (res.progress > 50) {
			// 		uploadTask.abort();
			// 	}
			// });
			break;
	}
};

// 获取本地缓存数据，且判断token是否过期
const getCacheData = () => {
	let token = uni.getStorageSync('token');
	let time = uni.getStorageSync('time');
	let refreshToken = uni.getStorageSync('refreshToken');
	let rightNow = new Date().getTime();
	let tokenExpired; // 1过期 ， 0未过期 ， 2没有token
	if (token) {
		// 如果有token, 判断是否过期
		if (rightNow - time > 5*60*1000) {
			// 5 分钟后 token  过期 ，提前5分钟刷新  300000
			tokenExpired = 1;
		} else {
			tokenExpired = 0;
		}
	} else {
		tokenExpired = 2;
	}
	return { token, time, refreshToken, rightNow, tokenExpired };
};

module.exports = {
	DELETE,
	PUT,
	POST,
	GET,
	downloadFile,
	uploadFile,
    POSTTOKEN,
};
